import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:toatool/src/data/remote/app_exceptions.dart';

import 'view_state_detail_controller.dart';

/// 基于ViewStateListController
abstract class ViewStateRefreshDetailController<T>
    extends ViewStateDetailController<T> {
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  RefreshController get refreshController => _refreshController;

  /// 下拉刷新
  /// init 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  @override
  Future<T?> mitRefresh({bool init = false}) async {
    try {
      var data = await loadData(queryData);
      if (data == null) {
        refreshController.refreshCompleted(resetFooterState: true);
        setEmpty();
      } else {
        onCompleted(data);
        detail = data;
        refreshController.refreshCompleted();
        refreshController.loadNoData();
        setIdle();
      }
      update();
      return data;
    } on AppException catch (e, s) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      refreshController.refreshFailed();
      setError(e, s, message: e.message);
      update();
      return null;
    } catch (e, s) {
      refreshController.refreshFailed();
      setError(e, s, message: 'データ異常');
      update();
      return null;
    }
  }

  // 加载数据
  @override
  Future<T> loadData([dynamic data]);

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }
}
